<?php

namespace App\Models\Member;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class FailedLogin extends Model
{
    use HasFactory;
    protected $table = 'failed_login';
    protected $primaryKey = 'ip';
    protected $keyType = 'string';
    public $timestamps = false;
    protected $fillable = [
        'ip',
        'count',
        'lastupdate',
    ];

    const LIMITTIMES=5;

    static function logincheck($ip) {
        $currTime = time();
        $login = self::find($ip);
        if($login) {
            if($currTime - $login['lastupdate'] > 900){
                $login->count=0;
                $login->lastupdate=$currTime;
                $login->save();
                $times=true;

            }else{
                if(self::LIMITTIMES-$login['count']>0){
                    $times=true;
                }else{
                    $times=false;
                }
            }
        }else{
            self::create([
                'ip' => $ip,
                'count' => 0,
                'lastupdate' => $currTime,
            ]);
            $times=true;

        }
        return $times;
    }

    static function update_failed($ip){
        $currTime = time();
        $login = self::find($ip);
        if($login) {
            $login->count=$login->count+1;
            $login->lastupdate = $currTime;
            $login->save();
            $times=max((self::LIMITTIMES - $login->count),0);
        }else{
            self::create([
                'ip' => $ip,
                'count' => 0,
                'lastupdate' => $currTime,
            ]);
            $times=self::LIMITTIMES;
        }
        return $times;
    }

}
